import { ElMessage } from "element-plus";
import type { AsyncData, UseFetchOptions } from "nuxt/dist/app/composables";

type Methods = "GET" | "POST";

export interface IResultData<T> {
  code: number;
  data: T;
}

class HYRequest {
  request<T = any>(
    url: string,
    method: Methods,
    data?: any,
    options?: UseFetchOptions<T>
  ): Promise<AsyncData<T, Error>> {
    return new Promise((resolve, reject) => {
      const newOptions: UseFetchOptions<T> = {
        // baseURL:typeof window ==="object"?'/api/':"http://localhost:8005",
        // baseURL: "http://localhost:8005",
        baseURL: "http://120.26.80.19:8005",
        method: method,
        ...options,
        onResponseError({ request, response, options, error }) {
          ElMessage.error(response._data.message)
            },
      };
      if (method === "GET") {
        newOptions.query = data;
      }
      if (method === "POST") {
        newOptions.body = data;
      }
      useFetch<T>(url, newOptions as any)
        .then((res) => {
          resolve(res as AsyncData<T, Error>);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  get<T = any>(url: string, params?: any, options?: UseFetchOptions<T>) {
    return this.request<T>(url, "GET", params, options);
  }

  post<T = any>(url: string, data?: any, options?: UseFetchOptions<T>) {
    return this.request<T>(url, "POST", data, options);
  }
}

export default new HYRequest();

